package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.Notification;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;
    @Autowired
    private WxPayV3Config wxPayV3Config;
    @Autowired
    private RSAAutoCertificateConfig config;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, String> createJsapi(String paymentType, String orderNo) {
        Long userId = AuthContextHolder.getUserId();
        // 1.封装保存本地交易记录
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);
        String paymentStatus = paymentInfo.getPaymentStatus(); //1401-未支付 1402-已支付
        //1.1 判断是否有交易记录
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentStatus)){
            throw new GuiguException(500, "交易已支付，不能重复支付");
        }
        // 2.对接微信支付接口获取小程序拉起微信支付页面所需参数
//2.1 构建支付service对象
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder().config(config).build();

        //2.2 创建预支付请求对象 用于产生微信交易
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        //TODO 开发中将应付金额设置为1分
        amount.setTotal(1);
        //amount.setTotal(paymentInfo.getAmount());
        request.setAmount(amount);
        request.setAppid(wxPayV3Config.getAppid());
        request.setMchid(wxPayV3Config.getMerchantId());
        request.setDescription(paymentInfo.getContent());
        request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
        request.setOutTradeNo(paymentInfo.getOrderNo());
        //TODO 小程序还未上线，只允许应用下开发者用户付款 设置付款者唯一标识
        Payer payer = new Payer();
        payer.setOpenid("odo3j4qp-wC3HVq9Z_D9C0cOr0Zs");
        request.setPayer(payer);
        //2.3 调用下单方法，得到响应，封装调起支付的参数
        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
        if (response != null) {
            String timeStamp = response.getTimeStamp();
            String nonceStr = response.getNonceStr();
            String packageVal = response.getPackageVal();
            String signType = response.getSignType();
            String paySign = response.getPaySign();
            Map<String, String> map = new HashMap<>();
            map.put("timeStamp", timeStamp);
            map.put("nonceStr", nonceStr);
            map.put("package", packageVal);
            map.put("signType", signType);
            map.put("paySign", paySign);
            return map;
        }
        return null;
    }

    /**
     * 查询订单支付状态:调用微信支付接口查询支付状态
     *
     * @param orderNo
     * @return
     */
    @Override
    public Boolean queryPayStatus(String orderNo) {
//        //1.构建支付service对象
//        JsapiServiceExtension service =
//                new JsapiServiceExtension.Builder().config(config).build();
//        //2.根据商户侧订单编号查询交易
//        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
//        request.setMchid(wxPayV3Config.getMerchantId());
//        request.setOutTradeNo(orderNo);
//        Transaction transaction = service.queryOrderByOutTradeNo(request);
//        //3.判断交易状态
//        if (transaction != null) {
//            log.info("订单对应交易结果:{}" + transaction);
//            Transaction.TradeStateEnum tradeState = transaction.getTradeState();
//            if (Transaction.TradeStateEnum.SUCCESS == tradeState) {
//                return true;
//            }
//        }
//        return false;
        // 模拟支付成功
        Transaction transaction = new Transaction();
        transaction.setTransactionId("wx"+ IdUtil.getSnowflakeNextId());
        transaction.setOutTradeNo(orderNo);
        //2.调用本地交易记录业务方法处理核心业务
        paymentInfoService.handlerPaymentInfo(transaction);
        return true;
    }

    @Override
    public Map<String, String> notifyPayResult(HttpServletRequest request) {
        //1. 验证签名获取请求体业务数据 防止出现虚假通知
        String signature = request.getHeader("Wechatpay-Signature");
        String serial = request.getHeader("Wechatpay-Serial");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String signaureType = request.getHeader("Wechatpay-Signature-Type");
        log.info("签名：{}，序列号：{}，随机数：{}，时间戳：{}，签名类型：{}", signature, serial, nonce, timestamp, signaureType);
        //1.2 获取请求体中参数
        String body = PayUtil.readData(request);
        log.info("请求体：{}", body);
        RequestParam requestParam = new RequestParam.Builder()
                .signature(signature)
                .serialNumber(serial)
                .nonce(nonce)
                .timestamp(timestamp)
                .body(body)
                .build();
        NotificationParser parser = new NotificationParser(config);
        Transaction transaction = parser.parse(requestParam, Transaction.class);
        //2. 进行幂等性处理
        if (transaction != null){
            String outTradeNo = transaction.getOutTradeNo();
            String key = "pay:notify:" + outTradeNo;
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, outTradeNo, 25, TimeUnit.HOURS);
            if (flag){
                //说明是首次处理
                Transaction.TradeStateEnum tradeState = transaction.getTradeState();
                //验证付款状态
                if (Transaction.TradeStateEnum.SUCCESS == tradeState){
                    //验证支付金额
                    Integer payTotal = transaction.getAmount().getTotal();
                    try {
                        if (payTotal.intValue() == 1){
                        paymentInfoService.handlerPaymentInfo(transaction);
                        //返回微信正确应答
                        Map<String, String> map = new HashMap<>();
                        map.put("code", "SUCCESS");
                        map.put("message", "成功");
                        return map;
                        }
                    }catch (Exception e){
                        redisTemplate.delete(key);
                        throw new RuntimeException(e);
                    }
                }

            }
        }
        return null;
    }
}
